package maxinshiSomeipTool20.GUI;

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.*;
import maxinshiSomeipTool20.GUI.packages.dataType.DataType;
import maxinshiSomeipTool20.GUI.packages.service.Service;
import maxinshiSomeipTool20.logMgr.LogMgr;
import java.util.function.Consumer;

public class AutosarSomeipToolMain {
    private Display display;
    private Shell shell;
    private Composite workArea;
    private CLabel statusLabel;
    private Composite workAreaContainer; // 右侧工作区容器
    private Composite mainContent; // 主内容区容器（包含左右两部分）
    
    // 工具栏相关变量
    private ToolItem toggleNavBtn;
    private ScrolledComposite leftNavContainer;
    private boolean isLeftNavVisible = true;

    private static final String[] MAIN_MODULES = {
        "datatype", "service", "SoftwareComponent", "Executable", 
        "Topology", "MachineManifest", "ServiceInstantiation", 
        "Mappings", "Clusters", "ModeDeclarationGroups", 
        "TransformationProps", "ServiceInstance"
    };
    private static final String DISABLED_ITEM_TEXT = "In developing";

    public AutosarSomeipToolMain() {
        initUI();
    }

    private void initUI() {
        display = new Display();
        shell = new Shell(display);
        shell.setText("AutoSAR SomeIP Tool");
        shell.setSize(1600, 900);
        shell.setMinimumSize(1000, 600);

        // 全局布局：1列，所有控件垂直排列
        GridLayout shellLayout = new GridLayout(1, false);
        shellLayout.marginWidth = 0;
        shellLayout.marginHeight = 0;
        shellLayout.verticalSpacing = 0; // 控件间无间隔
        shell.setLayout(shellLayout);

        // 层级顺序：菜单栏→工具栏→状态栏→主内容区（严格按此顺序）
        createMenuBar();
        createToolBar();
        createStatusBar();
        createMainContentArea(); // 主内容区在最下方，填满剩余空间

        updateStatus("Ready");
    }

    private void createToolBar() {
        ToolBar toolBar = new ToolBar(shell, SWT.FLAT | SWT.HORIZONTAL);
        // 工具栏布局：水平填满，固定在顶部，不占用额外垂直空间
        GridData toolBarGrid = new GridData(SWT.FILL, SWT.TOP, true, false);
        toolBar.setLayoutData(toolBarGrid);

        // 导航切换按钮
        toggleNavBtn = new ToolItem(toolBar, SWT.PUSH);
        toggleNavBtn.setText("Hide Navigation");
        toggleNavBtn.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                toggleLeftNavVisibility();
            }
        });

        // 分隔符
        new ToolItem(toolBar, SWT.SEPARATOR);

        // 刷新按钮
        ToolItem refreshBtn = new ToolItem(toolBar, SWT.PUSH);
        refreshBtn.setText("Refresh");
        refreshBtn.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                refreshAllLayout();
                updateStatus("Refresh Successed");
            }
        });
    }

    // 核心修正：导航显隐逻辑（确保工作区垂直填满）
    private void toggleLeftNavVisibility() {
        isLeftNavVisible = !isLeftNavVisible;
        GridLayout mainLayout = (GridLayout) mainContent.getLayout();

        if (isLeftNavVisible) {
            mainLayout.numColumns = 2;
            leftNavContainer.setVisible(true);
            GridData leftGrid = (GridData) leftNavContainer.getLayoutData();
            leftGrid.widthHint = 250;
            leftGrid.exclude = false; // 关键：取消排除
            leftNavContainer.setLayoutData(leftGrid);
            toggleNavBtn.setText("Hide Navigation");
        } else {
            mainLayout.numColumns = 1;
            leftNavContainer.setVisible(false);
            GridData leftGrid = (GridData) leftNavContainer.getLayoutData();
            leftGrid.widthHint = 0;
            leftGrid.exclude = true; // 关键：排除该控件，让它不参与布局计算
            leftNavContainer.setLayoutData(leftGrid);
            toggleNavBtn.setText("Show Navigation");
        }

        // 强制刷新布局
        mainContent.layout(true, true);
        shell.layout(true, true);
        shell.redraw();
    }


    // 新增：全局布局刷新方法（确保所有层级正确重绘）
    private void refreshAllLayout() {
        // 从内到外刷新所有容器
        workArea.layout(true, true);
        workAreaContainer.layout(true, true);
        mainContent.layout(true, true);
        shell.layout(true, true); // 最后刷新整个窗口
    }

    private MenuItem createMenuItem(Menu parent, String text, Consumer<SelectionEvent> listener) {
        MenuItem item = new MenuItem(parent, SWT.PUSH);
        item.setText(text);
        item.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                if (listener != null) {
                    listener.accept(e);
                }
            }
        });
        return item;
    }

    // ====================== 核心修改1：在File前添加Home菜单 ======================
    private void createMenuBar() {
        Menu menuBar = new Menu(shell, SWT.BAR);

        // 新增：Home菜单（放在File按钮前）
        MenuItem homeItem = new MenuItem(menuBar, SWT.PUSH);
        homeItem.setText("Home");
        homeItem.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                // 核心逻辑：点击Home→显示左侧导航+加载datatype页面
                goToHomePage();
            }
        });

        // 新增：Home与File之间的分隔符
        new MenuItem(menuBar, SWT.SEPARATOR);

        // 原有File菜单（位置不变，在Home后）
        MenuItem fileItem = new MenuItem(menuBar, SWT.CASCADE);
        fileItem.setText("File");
        Menu fileMenu = new Menu(shell, SWT.DROP_DOWN);
        fileItem.setMenu(fileMenu);
        createMenuItem(fileMenu, "New", e -> {
            updateStatus("新建文件");
            showWorkAreaMessage("新建文件功能尚未实现");
        });
        createMenuItem(fileMenu, "Open", e -> {
            updateStatus("打开文件");
            showWorkAreaMessage("打开文件功能尚未实现");
        });
        createMenuItem(fileMenu, "Save", e -> {
            updateStatus("保存文件");
            showWorkAreaMessage("保存文件功能尚未实现");
        });
        new MenuItem(fileMenu, SWT.SEPARATOR);
        createMenuItem(fileMenu, "Exit", e -> shell.dispose());

        // 原有Project菜单（位置不变）
        MenuItem projectItem = new MenuItem(menuBar, SWT.CASCADE);
        projectItem.setText("Project");
        Menu projectMenu = new Menu(shell, SWT.DROP_DOWN);
        projectItem.setMenu(projectMenu);
        createMenuItem(projectMenu, "New Project", e -> {
            updateStatus("新建项目");
            showWorkAreaMessage("新建项目功能尚未实现");
        });
        createMenuItem(projectMenu, "Import Project", e -> {
            updateStatus("导入项目");
            showWorkAreaMessage("导入项目功能尚未实现");
        });
        createMenuItem(projectMenu, "Export Project", e -> {
            updateStatus("导出项目");
            showWorkAreaMessage("导出项目功能尚未实现");
        });
        createMenuItem(projectMenu, "Properties", e -> {
            updateStatus("项目属性");
            showWorkAreaMessage("项目属性功能尚未实现");
        });

        // 原有Load菜单（位置不变）
        MenuItem loadItem = new MenuItem(menuBar, SWT.CASCADE);
        loadItem.setText("Load");
        Menu loadMenu = new Menu(shell, SWT.DROP_DOWN);
        loadItem.setMenu(loadMenu);
        createMenuItem(loadMenu, "Load Configuration", e -> {
            updateStatus("加载配置");
            showWorkAreaMessage("加载配置功能尚未实现");
        });
        createMenuItem(loadMenu, "Load Template", e -> {
            updateStatus("加载模板");
            showWorkAreaMessage("加载模板功能尚未实现");
        });
        createMenuItem(loadMenu, "Load Recent", e -> {
            updateStatus("加载最近文件");
            showWorkAreaMessage("加载最近文件功能尚未实现");
        });
        
        shell.setMenuBar(menuBar);
    }

    // ====================== 核心修改2：Home菜单点击逻辑（跳转到datatype页面） ======================
    private void goToHomePage() {
        // 1. 强制显示左侧导航（如果隐藏则切换显示）
        if (!isLeftNavVisible) {
            toggleLeftNavVisibility();
        }

        // 2. 清空工作区旧内容
        safeClearWorkArea();

        // 3. 加载datatype的默认页面（默认加载第一个子菜单ApplicationTypes）
        String defaultSubModule = "ApplicationTypes"; // datatype的第一个子菜单
        boolean isLoaded = DataType.createSubModulePanel(defaultSubModule, workArea);

        // 4. 处理加载结果（加载失败则提示）
        if (isLoaded) {
            updateStatus("已回到主页：datatype > " + defaultSubModule);
        } else {
            showWorkAreaMessage("主页模块加载失败，请选择左侧datatype子菜单");
            updateStatus("主页加载失败");
        }

        // 5. 刷新布局，确保页面显示正常
        refreshAllLayout();
    }

    private void createStatusBar() {
        Composite statusBar = new Composite(shell, SWT.BORDER);
        // 状态栏布局：水平填满，固定高度
        GridData statusBarGrid = new GridData(SWT.FILL, SWT.TOP, true, false);
        statusBarGrid.heightHint = 25; // 固定高度，不挤压其他区域
        statusBar.setLayoutData(statusBarGrid);
        statusBar.setLayout(new FillLayout());
        
        statusLabel = new CLabel(statusBar, SWT.LEFT);
        statusLabel.setText("Ready");
    }

    private void createMainContentArea() {
        // 主内容区：包含左侧导航和右侧工作区，位于状态栏下方
        mainContent = new Composite(shell, SWT.NONE);
        GridData mainContentGrid = new GridData(SWT.FILL, SWT.FILL, true, true);
        mainContent.setLayoutData(mainContentGrid);
        mainContent.setLayout(new GridLayout(2, false)); // 默认2列

        // 左侧导航容器（保持不变）
        ScrolledComposite treeScroll = new ScrolledComposite(mainContent, SWT.BORDER | SWT.V_SCROLL);
        leftNavContainer = treeScroll;
        GridData treeGrid = new GridData(SWT.FILL, SWT.FILL, false, true);
        treeGrid.widthHint = 250;
        treeScroll.setLayoutData(treeGrid);
        treeScroll.setExpandHorizontal(true);
        treeScroll.setExpandVertical(true);

        Composite treePanel = new Composite(treeScroll, SWT.NONE);
        treePanel.setLayout(new FillLayout());
        Tree tree = createFunctionTree(treePanel);
        treeScroll.setContent(treePanel);
        treeScroll.setMinSize(treePanel.computeSize(SWT.DEFAULT, SWT.DEFAULT));

        // 修复：右侧工作区容器，显式设置 verticalAlignment
        workAreaContainer = new Composite(mainContent, SWT.BORDER);
        GridData workContainerGrid = new GridData(SWT.FILL, SWT.FILL, true, true);
        workContainerGrid.grabExcessVerticalSpace = true;  // 抢占垂直空间
        workContainerGrid.verticalAlignment = SWT.FILL;    // 关键：垂直填满
        workAreaContainer.setLayoutData(workContainerGrid);
        workAreaContainer.setLayout(new GridLayout(1, false));

        // 工作区（保持不变）
        workArea = new Composite(workAreaContainer, SWT.NONE);
        workArea.setLayout(new GridLayout(1, false));
        GridData workAreaGrid = new GridData(SWT.FILL, SWT.FILL, true, true);
        workAreaGrid.grabExcessVerticalSpace = true;
        workAreaGrid.verticalAlignment = SWT.FILL;         // 也建议加上
        workArea.setLayoutData(workAreaGrid);

        showInitialWorkAreaContent();
        refreshAllLayout();

        // 树选择事件（保持不变）
        tree.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                TreeItem selected = (TreeItem) e.item;
                if (selected == null) return;

                // 过滤禁用节点（如“模块开发中”）
                if (DISABLED_ITEM_TEXT.equals(selected.getText())) {
                    safeClearWorkArea();
                    updateStatus("提示：该模块正在开发中，暂不支持");
                    return;
                }

                // 清理工作区旧内容
                safeClearWorkArea();
                String rootModule = "";    // 根模块（如datatype、service）
                String subModule = "";     // 子模块（如ApplicationTypes）
                boolean isSubModuleLoaded = false;

                // 1. 确定根模块和子模块（统一参数格式）
                TreeItem parentItem = selected.getParentItem();
                if (parentItem != null) {
                    // 子菜单点击：父节点是根模块，当前节点是子模块
                    rootModule = parentItem.getText();
                    subModule = selected.getText();
                } else {
                    // 根目录点击：当前节点是根模块，需找第一个有效子模块
                    rootModule = selected.getText();
                    if (selected.getItemCount() > 0) {
                        TreeItem firstChild = selected.getItem(0);
                        subModule = firstChild.getText();
                        // 子模块禁用时置空（后续处理）
                        if (DISABLED_ITEM_TEXT.equals(subModule)) {
                            subModule = "";
                        }
                    }
                    // 根目录无有效子模块时，subModule保持空
                }

                // 2. 统一调用通用方法加载面板（消除重复的switch case）
                if (!subModule.isEmpty()) {
                    isSubModuleLoaded = loadModulePanel(rootModule, subModule);
                } else {
                    // 无有效子模块：留空并提示
                    isSubModuleLoaded = true;
                    if (selected.getItemCount() > 0) {
                        updateStatus("已选择: " + rootModule + "（子模块开发中，暂空）");
                    } else {
                        updateStatus("已选择: " + rootModule + "（暂无子功能，后续扩展）");
                    }
                }

                // 3. 处理加载结果
                if (isSubModuleLoaded && !subModule.isEmpty()) {
                    updateStatus("已选择: " + rootModule + " > " + subModule);
                    refreshAllLayout();
                } else if (!isSubModuleLoaded) {
                    showWorkAreaMessage("子模块[" + subModule + "]尚未实现");
                    updateStatus("错误：子模块未实现");
                }
            }
        });
    }

    // 通用模块加载方法（提取重复的switch case逻辑）
    private boolean loadModulePanel(String rootModule, String subModule) {
        switch (rootModule) {
            case "datatype":
                return DataType.createSubModulePanel(subModule, workArea);
            case "service":
                return Service.createSubModulePanel(subModule, workArea);
            default:
                // 其他模块暂不支持，默认视为加载成功（留空）
                return true;
        }
    }
    
    // 以下方法保持不变
    private Tree createFunctionTree(Composite parent) {
        Tree tree = new Tree(parent, SWT.NONE);
        for (String moduleName : MAIN_MODULES) {
            TreeItem moduleItem = new TreeItem(tree, SWT.NONE);
            moduleItem.setText(moduleName);
            addSubFunctionTree(moduleItem, moduleName);
        }
        for (TreeItem item : tree.getItems()) {
            item.setExpanded(true);
        }
        return tree;
    }

    private void addSubFunctionTree(TreeItem parent, String moduleName) {
        switch (moduleName) {
            case "datatype":
                DataType.addSubFunctions(parent, workArea);
                break;
            case "service": 
                Service.addSubFunctions(parent, workArea);
                break;
            default:
                LogMgr.log("unknown module Name: " + moduleName);
                TreeItem tipItem = new TreeItem(parent, SWT.NONE);
                tipItem.setText(DISABLED_ITEM_TEXT);
                tipItem.setForeground(display.getSystemColor(SWT.COLOR_GRAY));
                break;
        }
    }

    private void safeClearWorkArea() {
        for (Control control : workArea.getChildren()) {
            if (control != null && !control.isDisposed()) {
                control.dispose();
            }
        }
    }

    // 原有注释方法（保留，暂不使用）
    private void showModuleDesc(String moduleName) {
        Label descLabel = new Label(workArea, SWT.CENTER);
        descLabel.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
        switch (moduleName) {
            case "datatype":
                descLabel.setText("数据类型模块\n\n包含5个子模块：\n1. ApplicationTypes（应用数据类型）\n2. BaseTypes（基础数据类型）\n3. CompuMethods（计算方法）\n4. DataTypeMappings（数据类型映射）\n5. ImplementationTypes（实现数据类型）");
                break;
            case "service":
                descLabel.setText("服务模块\n\n包含2个子模块：\n1. Interface（服务接口定义）\n2. InterfaceDeployment（服务接口部署）");
                break;
            default:
                descLabel.setText("[" + moduleName + "]模块\n\n请选择下方子模块进行配置");
                break;
        }
    }

    private void showInitialWorkAreaContent() {
        Label label = new Label(workArea, SWT.CENTER);
        label.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
        label.setText("欢迎使用 AutoSAR SomeIP 工具\n\n请从左侧选择一个功能项进行操作");
    }

    private void showWorkAreaMessage(String message) {
        safeClearWorkArea();
        Label label = new Label(workArea, SWT.CENTER);
        label.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
        label.setText(message);
        refreshAllLayout();
    }

    private String getTreeItemPath(TreeItem item) {
        StringBuilder path = new StringBuilder(item.getText());
        TreeItem parent = item.getParentItem();
        while (parent != null) {
            path.insert(0, parent.getText() + " > ");
            parent = parent.getParentItem();
        }
        return path.toString();
    }

    public void updateStatus(String message) {
        statusLabel.setText(message);
    }

    public void open() {
        shell.open();
        while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) {
                display.sleep();
            }
        }
        display.dispose();
    }

    public static void main(String[] args) {
        new AutosarSomeipToolMain().open();
    }
}